package com.crypto;

import com.google.protobuf.ByteString;
import org.apache.commons.codec.binary.Hex;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Sha256 {

    /**
     *
     * @param input byte数组
     * @return
     */
    public static byte[] hash(byte[] input) {
        try {
            return MessageDigest.getInstance("SHA-256").digest(input);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return new byte[0];
    }

    /**
     *
     * @param input byte数组
     * @return
     */
    public static String hashstr(byte[] input){
        return Hex.encodeHexString(hash(input));
    }

    /**
     *
     * @param input String
     * @return String
     */
    public static String hashstr(String input) {
        ByteString iptb = ByteString.copyFromUtf8(input);
        return Hex.encodeHexString(hash(iptb.toByteArray()));
    }

    /**
     *
     * @param input String
     * @return byte数组
     */
    public static byte[] hashToBytes(String input) {
        ByteString iptb = ByteString.copyFromUtf8(input);
        return hash(iptb.toByteArray());
    }
}
